<?php
namespace lib\JhWechat;

/**
 * 文章拼装
 * @Auth: JH <hu@lunaz.cn>
 * Class Article
 * @package lib\JhWechat
 */
class Article extends Media
{

    protected $art = array();

    /**
     * @param array $options
     * @param string $access_token
     */
    function __construct(array $options = array(), $access_token = '')
    {
        if ($access_token) {
            parent::$accessToken = $access_token;
        }
        if ($options) {
            parent::$config = $options;
        }
        parent::__construct();
    }

    function addNews(
        $title = '文章标题', $content = '文章内容', $thumb = '缩略图', $author = '作者', $digest = '摘要', $show_pic = 1,
        $url = 'http://yourWebsite.com'
    ) {
        if (is_file($thumb)) {
            $thumb_id = $this->uploadMedia($thumb, 'image', false, 'media_id');
        } else {
            $thumb_id = $thumb;
        }
        if (count($this->art) < 8) {
            $this->art[] = array(
                'title' => $title,
                'thumb_media_id' => $thumb_id,
                'author' => $author,
                'digest' => $digest,
                'show_cover_pic' => $show_pic,
                'content' => $content,
                'content_source_url' => $url
            );
        }
        return $this;
    }

    /**
     * 提交永久图文素材
     * @return false|media_id
     * @throws Exception
     */
    function pushNews()
    {
        if (empty($this->art)) {
            return false;
        }
        $result = $this->http(
            $this->makeUrl('/material/add_news', $this->getAccessToken()),
            array('articles' => $this->art)
        );
        if (isset($result['media_id'])) {
            return $result['media_id'];
        }
        return false;
    }

    /**
     * 修改永久图文素材, 注意，调用更新接口先使用addNews方法拼装图文格式
     * 支持链式$article->addNews(....)->updateNews(...)
     *
     * @param string $media_id
     * @param int $index
     *
     * @return bool
     * @throws Exception
     */
    function updateNews($media_id, $index = 0)
    {
        if (empty($this->art)) {
            return false;
        }
        $result = $this->http(
            $this->makeUrl('/material/update_news', $this->getAccessToken()),
            array(
                'media_id' => $media_id,
                'index' => (int)min(7, $index),
                'articles' => $this->art[0]
            )
        );
        return $result['errcode'] === 0;
    }
}
